<?php
namespace Admin\Model;
use Think\Model\RelationModel;

class MajorModel extends RelationModel {

	protected $_validate = array(
		array('id', 'require', 'id不能为空！'),
		array('name', 'require', '名称不能为空！'),
		array('academy_id', 'require', '学院不能为空！', 1),
	);

	protected $_auto = array(
		array('id', 'intval', 2, 'function'),
		array('academy_id', 'intval', 3, 'function'),
	);

	protected $_link = array(
		'academy' => array(
			'mapping_type'	=> self::BELONGS_TO,
			'class_name'	=> 'Academy',
			'foreign_key'	=> 'academy_id',
		),
		'classes' => array(
		    'mapping_type'  => self::HAS_MANY,
		    'class_name'    => 'Class',
		    'foreign_key'   => 'major_id',
		),
		'courses' => array(
		    'mapping_type'  => self::HAS_MANY,
		    'class_name'    => 'Course',
		    'foreign_key'   => 'major_id',
		),
	);

	public function checkUnique($major) {
		$map['name'] = $major['name'];
		$map['academy_id'] = (int)$major['academy_id'];
		return !M('Major')->where($map)->find();
	}

	public function hasChildObj($id) {
		$result = $this->where(array('id' => $id))->relation('classes')->find();
		if($result['classes']) {
			$this->error = '该专业下面还有班级未删除，请先删除这些班级！';
			return true;
		}
		$result = array();
		$result = $this->where(array('id' => $id))->relation('courses')->find();
		if($result['courses']) {
			$this->error = '该专业下面还有课程未删除，请先删除这些课程！';
			return true;
		}
		return false;
	}

}
